<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="1120px">
    <a-form ref="formRef" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="validatorRules">
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">委托单位信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="委托单位" name="entName">
            <!-- <j-dict-select-tag v-model:value="formData.entName" dictCode="lab_enterprise,ent_name,ent_name"
              :show-choose-option="false" :disabled="disabled" /> -->
            <a-input v-model:value="formData.entName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="单位地址" name="entAddress">
            <a-input v-model:value="formData.entAddress" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办/送样人" name="handler">
            <a-input v-model:value="formData.handler" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办日期" name="handlDate">
            <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="formData.handlDate" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系人" name="contacter">
            <a-input v-model:value="formData.contacter" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话" name="phone">
            <a-input v-model:value="formData.phone" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">承接单位信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="承接单位" name="carryName">
            <a-select v-model:value="formData.carryName" :disabled="disabled">
              <a-select-option value="中国石油西南油气田分公司天然气研究院气田开发化学实验室">中国石油西南油气田分公司天然气研究院气田开发化学实验室</a-select-option>
              <a-select-option value="实验中心">实验中心</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="8">
          <a-form-item label="承接地址" name="carryAddress">
            <a-input v-model:value="formData.carryAddress" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="8">
          <a-form-item label="联系信息" name="carryContact">
            <a-input v-model:value="formData.carryContact" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="8">
          <a-form-item label="编号规则" name="codeRule">
            <a-select v-model:value="formData.codeRule" :show-choose-option="false" :disabled="disabled">
            </a-select>
          </a-form-item>
        </a-col>
      </a-row> -->

      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">委托样品信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="取/送样" name="takeSendSample">
            <j-dict-select-tag v-model:value="formData.takeSendSample" dictCode="take_send" :show-choose-option="false" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品大类" name="sampleTypeId">
            <a-input style="display: none" v-model:value="formData.sampleType"></a-input>
            <j-dict-select-tag
              v-model:value="formData.sampleTypeId"
              dictCode="lab_items,name,id,type='A'"
              :show-choose-option="false"
              :disabled="disabled"
              @change="handleTypeChange"
              ref="dictSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品类别" name="sampleSort">
            <a-input style="display: none" v-model:value="formData.sampleSort" :disabled="disabled"></a-input>
            <!--循环加载样品类别下拉选项 -->
            <a-select v-model:value="formData.sampleSortId" style="width: 100%" @change="handleSortChange">
              <a-select-option v-for="sort in formData.sortsList" key="{{sort.id}}" :value="sort.id.toString()" :label="sort.name">
                {{ sort.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-item label="样品存储说明" v-bind="validateInfos.sampleStoreRemark">
            <a-input v-model:value="formData.sampleStoreRemark" placeholder="" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-item label="样品名称" name="sampleName">
            <a-input v-model:value="formData.sampleName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品数量" name="sampleNum">
            <a-input-number v-model:value="formData.sampleNum" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品包装" name="samplePack">
            <a-input v-model:value="formData.samplePack" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品存储" name="sampleStore">
            <j-dict-select-tag v-model:value="formData.sampleStore" dictCode="sample_store" :show-choose-option="false" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品处置" name="sampleDispose">
            <j-dict-select-tag v-model:value="formData.sampleDispose" dictCode="sample_dispose" :show-choose-option="false" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">检测项目信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <!-- <a-form-item label="检测项目" name="testItems">
            <a-select v-model:value="formData.AtestItems" mode="multiple" style="display: none"></a-select>
            <a-select v-model:value="formData.AtestItemsIds" mode="multiple" :options="options" style="width: 950px"></a-select>
          </a-form-item> -->
          <a-form-item label="检测项目" name="testItems">
            <a-select v-model:value="formData.AtestItems" mode="multiple" style="display: none"></a-select>
            <!-- <a-select v-model:value="formData.AtestItemsIds" mode="multiple" :options="options" style="width: 950px"></a-select> -->
            <a-select
              v-model:value="formData.AtestItemsIds"
              mode="multiple"
              placeholder="请选择实验项目"
              option-label-prop="label"
              style="width: 950px"
              @change="handleLabItems"
            >
              <a-select-option v-for="item in options1" :value="item.value" :label="item.label">{{ item.labelText }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="方法/标准" name="wayNorm">
            <j-dict-select-tag v-model:value="formData.wayNorm" dictCode="way_norm" :show-choose-option="false" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="上传检测依据" :label-col="{ span: 7 }" name="testItemsAtta">
            <JUpload v-model:value="formData.testItemsAtta" :disabled="disabled"></JUpload>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="合同附件" name="conAtta">
            <JUpload v-model:value="formData.conAtta" :disabled="disabled"></JUpload>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- <a-row>
        <a-col :span="8">
          <a-form-item label="其他说明" name="remark">
            <a-input v-model:value="formData.remark" style="width: 950px;" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row> -->
      <!-- <a-tabs  style="display: none;">
        <a-tab-pane tab="样品信息">
          <div>
            <a-row type="flex" style="margin-bottom: 3px;">
              <a-col :span="3" style="text-align: center;">样品编号</a-col>
              <a-col :span="4" style="text-align: center;">样品名称</a-col>
              <a-col :span="2" style="text-align: center;">规格型号</a-col>
              <a-col :span="2" style="text-align: center;">产品批号</a-col>
              <a-col :span="3" style="text-align: center;">取样日期</a-col>
              <a-col :span="2" style="text-align: center;">样品量</a-col>
              <a-col :span="3" style="text-align: center;">样品外观</a-col>
              <a-col :span="3" style="text-align: center;">其他说明</a-col>
              <a-col :span="2" style="text-align: center;">操作</a-col>
            </a-row>
            <a-row type="flex" style="margin-bottom: 3px;height: 30px;" gutter="1px"
              v-for="(item, index) in formData.labSampleList" :key="index">
              <a-col :span="2" style="display: none">
                <a-form-item>
                  <a-input placeholder="id" v-model:value="item.id" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.samNum" style="width: 134px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.samName" style="width: 178px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.model" style="width: 87px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.lotNum" style="width: 90px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="item.samDate" style="max-width: 125px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.samQuality" style="width: 88px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.samAppear" style="width: 130px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input placeholder="" v-model:value="item.remark" style="width: 130px;" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item >
                  <Icon icon="ant-design:minus-outlined" @click="delRowCustom(index)"
                    style="fontsize: 20px;width: 85px;" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-button type="dashed" style="width: 98%; margin-top: 10px;" @click="addRowCustom" :disabled="disabled">
              <Icon icon="ph:plus-bold" />
              添加样品信息
            </a-button>
          </div>
        </a-tab-pane>
      </a-tabs> -->
    </a-form>
    <template v-slot:footer>
      <a-button type="default" @click="closeModal"> 取消 </a-button>
      <a-button type="danger" @click="showAuditModal('no')">不同意</a-button>
      <a-button type="primary" @click="showAuditModal('yes')">同意</a-button>
    </template>
  </BasicModal>
  <AuditModal @register="regAuditModal" @ok1="closeModals"></AuditModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, computed, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { saveOrUpdate, labSampleList, labSortsList, getExperimentProjects } from '../LabEntrust.api';
  import AuditModal from './FirstAuditModal.vue';
  import { SelectProps } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'FirstAuditModal',
    components: { BasicModal, JDictSelectTag, JUpload, AuditModal },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const formRef = ref();
      const disabled = ref(false);
      const options = ref<SelectProps['options']>([]);
      const options1 = ref<SelectProps['options']>([]);
      const labelCol = reactive({
        xs: { span: 24 },
        sm: { span: 5 },
      });
      const wrapperCol = reactive({
        xs: { span: 24 },
        sm: { span: 16 },
      });
      const validatorRules = {};
      const dictSelect = ref();
      const formData = reactive({
        id: null,
        entName: '',
        entAddress: '',
        handler: '',
        handlDate: null,
        contacter: '',
        phone: '',
        takeSendSample: '',
        sampleTypeId: '',
        sampleType: '',
        sampleSortId: '',
        sampleSort: '',
        sampleName: '',
        sampleNum: '',
        samplePack: '',
        sampleStore: '',
        sampleDispose: '',
        testItemsIds: '',
        testItems: '',
        testItemsAtta: '',
        wayNorm: '',
        remark: '',
        conAtta: '',
        auditMark: '制单中',
        labSampleList: [],
        samPrep: '',
        samForm: '',
        reportCode: '',
        reportType: '',
        deliverData: '',
        reportNum: '',
        deliverWay: '',
        checkCost: '',
        subItems: '',
        subOrg: '',
        seekMark: '',
        reviewA: 1,
        reviewB: 1,
        reviewC: 1,
        reviewD: 1,
        reviewE: 1,
        reviewF: 1,
        reviewG: 1,
        reviewH: 1,
        reviewI: 1,
        entrustType: '委托检验',
        carryName: '',
        carryAddress: '',
        carryContact: '',
        codeRule: '',
        auxiliarySample: '',
        auxiliaryNum: '',
        allotStatus: '未分配',
        showDivA: false,
        showDivB: false,
        sortsList: [],
        itemsList: [],
        AtestItemsIds: [],
        AtestItems: [],
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        disabled.value = data.disabled;
        reset();
        if (unref(isUpdate.value)) {
          rowId.value = data.record.id;
          Object.assign(formData, data.record);
          let params = { id: formData.id };
          const customerList = await labSampleList(params);
          formData.labSampleList = customerList;
          //编辑或查看进入页面样品大类不为空时，加载样品类型下拉数据
          if (formData.sampleTypeId != null || formData.sampleTypeId != '') {
            formData.sortsList = (await labSortsList({ id: formData.sampleTypeId })).records;
          }
          //编辑或查看进入页面样品类型不为空时，加载实验项目下拉数据
          if (formData.sampleSortId != null && formData.sampleSortId != '') {
            //加载实验项目
            loadItems();
          }
          //编辑或查看进入页面加载实验项目下拉数据,并把已有的数据转换成数组
          if (formData.testItemsIds != null && formData.testItemsIds != '') {
            // 将JSON字符串对象转换为对象数组
            formData.AtestItemsIds = JSON.parse(formData.testItemsIds);
            formData.AtestItems = JSON.parse(formData.testItems);
          }
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '详情' : '初审'));
      const { userInfo } = useUserStore();

      //动态添加行
      function addRowCustom() {
        formData.labSampleList.push({});
      }

      //删除行
      function delRowCustom(index) {
        formData['labSampleList'].splice(index, 1);
        formData.labSampleList.splice(index, 1);
      }
      function reset() {
        formData.id = null;
        formData.entName = '';
        formData.entAddress = '';
        formData.handler = '';
        formData.handlDate = null;
        formData.contacter = '';
        formData.phone = '';
        formData.takeSendSample = '';
        formData.sampleTypeId = '';
        formData.sampleType = '';
        formData.sampleSortId = '';
        formData.sampleSort = '';
        formData.sampleName = '';
        formData.sampleNum = '';
        formData.samplePack = '';
        formData.sampleStore = '';
        formData.sampleDispose = '';
        formData.testItemsIds = '';
        formData.testItems = '';
        formData.testItemsAtta = '';
        formData.wayNorm = '';
        formData.remark = '';
        formData.conAtta = '';
        formData.auditMark = '制单中';
        formData.labSampleList = [];
        formData.samPrep = '';
        formData.samForm = '';
        formData.reportCode = '';
        formData.reportType = '';
        formData.deliverData = '';
        formData.reportNum = '';
        formData.deliverWay = '';
        formData.checkCost = '';
        formData.subItems = '';
        formData.subOrg = '';
        formData.seekMark = '';
        formData.reviewA = 1;
        formData.reviewB = 1;
        formData.reviewC = 1;
        formData.reviewD = 1;
        formData.reviewE = 1;
        formData.reviewF = 1;
        formData.reviewG = 1;
        formData.reviewH = 1;
        formData.reviewI = 1;
        formData.entrustType = '委托检验';
        formData.carryName = '中国石油西南油气田分公司天然气研究院气田开发化学实验室';
        formData.carryAddress = '四川省成都市天府新区华阳天研路218号 610213';
        formData.carryContact = '印  敬/(028)85604123  13880486175  张楠革/(028)85604594  13618090676';
        formData.codeRule = 'WXY';
        formData.auxiliarySample = '0';
        formData.auxiliaryNum = '';
        formData.allotStatus = '未分配';
        formData.showDivA = false;
        formData.showDivB = false;
        formData.sortsList = [];
        formData.itemsList = [];
        formData.AtestItemsIds = [];
        formData.AtestItems = [];
      }

      //样品大类改变时加载样品类型下拉数据
      async function handleTypeChange() {
        const dictData = dictSelect.value.dictOptions;
        let selectedType = dictData.filter((item) => {
          return item.value === formData.sampleTypeId;
        });
        if (selectedType.length > 0) formData.sampleType = selectedType[0].label;
        const typeId = formData.sampleTypeId;
        let params = { id: typeId };

        //如果样品类型已有选中的数据先清空已选中的数据
        handleClearSort();
        //如果实验项目已有选中的数据先清空已选中的数据
        handleClearItems();
        //清空样品类型下拉数据
        formData.sortsList = [];
        //重新给样品类型下拉赋值
        formData.sortsList = (await labSortsList(params)).records;
        options1.value = [];
      }

      //样品类别类改变时
      async function handleSortChange(value, option) {
        formData.sampleSort = option.label;
        //如果实验项目已有选中的数据先清空已选中的数据
        handleClearItems();
        //重新加载实验项目
        loadItems();
      }
      //加载实验项目
      async function loadItems() {
        const SortId = formData.sampleSortId;
        let params = { id: SortId };
        //清空实验项目下拉数据
        formData.itemsList = [];
        //重新给实验项目下拉框赋值
        // formData.itemsList = (await labSortsList(params)).records;
        // options.value = [];
        // for (let i = 0; i < formData.itemsList.length; i++) {
        //   options.value.push({
        //     label: formData.itemsList[i].name,
        //     value: formData.itemsList[i].id,
        //   });
        // }
        try {
          let result = await getExperimentProjects(params);
          if (result.code === 200) {
            if (result.result.length > 0) {
              formData.itemsList = result.result;
              options1.value = [];
              for (let i = 0; i < formData.itemsList.length; i++) {
                options1.value.push({
                  label: formData.itemsList[i].name,
                  value: formData.itemsList[i].id,
                  labelText: formData.itemsList[i].itemsBasisName,
                });
              }
            }
          }
        } catch (error) {
          createMessage.error(error);
        }
      }
      // 实验项目change事件回到
      const handleLabItems = (value, option) => {
        formData.AtestItems = [];
        if (option.length > 0) {
          option.forEach((element) => {
            formData.AtestItems.push(element.label);
          });
        }
      };
      //清空已选中的样品类型数据
      function handleClearSort() {
        if (formData.sampleSortId != null || formData.sampleSortId != '') {
          formData.sampleSortId = '';
          formData.sampleSort = '';
        }
      }
      //清空已选中的实验项目数据
      function handleClearItems() {
        if (formData.AtestItemsIds != null || formData.AtestItemsIds != '') {
          formData.AtestItemsIds = [];
          formData.AtestItems = [];
          formData.testItems = '';
          formData.testItemsIds = '';
        }
      }
      //把选中的实验项目由数组转成JSON字符串
      function itemsArrayToJson() {
        if (formData.AtestItems != null || formData.AtestItems != '') {
          formData.testItems = JSON.stringify(formData.AtestItems);
          formData.testItemsIds = JSON.stringify(formData.AtestItemsIds);
        }
      }

      async function handleSubmit() {
        formRef.value
          .validate()
          .then(async () => {
            try {
              setModalProps({ confirmLoading: true });
              await saveOrUpdate(formData, unref(isUpdate));
              closeModal();
              emit('success');
            } finally {
              setModalProps({ confirmLoading: false });
            }
          })
          .catch((error: ValidateErrorEntity<any>) => {
            console.log('error', error);
          });
      }

      const [regAuditModal, { openModal: openAuditModal, closeModal: closeAuditModal }] = useModal();

      async function showAuditModal(str) {
        itemsArrayToJson();
        openAuditModal(true, { formData, str });
      }
      async function closeModals() {
        //延迟0.5秒关闭弹框
        setTimeout(() => {
          //关闭子modal
          closeAuditModal();
          //关闭父 modal
          closeModal();
          //刷新列表
          emit('success');
        }, 1000);
      }

      return {
        formRef,
        validatorRules,
        formData,
        getTitle,
        labelCol,
        wrapperCol,
        disabled,
        options,
        options1,
        dictSelect,
        registerModal,
        addRowCustom,
        delRowCustom,
        handleSubmit,
        closeModal,
        regAuditModal,
        openAuditModal,
        closeAuditModal,
        showAuditModal,
        closeModals,
        handleTypeChange,
        handleSortChange,
        itemsArrayToJson,
        handleLabItems,
        // updateSign,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-btn {
    padding: 0 10px;
    margin-left: 3px;
  }

  .ant-form-item-control {
    line-height: 0px;
  }

  /** 主表单行间距 */
  .ant-form .ant-form-item {
    margin-bottom: 10px;
  }

  /** Tab页面行间距 */
  .ant-tabs-content .ant-form-item {
    margin-bottom: 0px;
  }

  .hClass {
    width: 160px;
    height: 20px;
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 550;
    color: #009688;
    line-height: 14px;
  }

  .ant-form-item-label {
    width: 150px;
    height: 20px;
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: #727272;
    line-height: 20px;
  }

  .ant-input {
    width: 220px;
    height: 32px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #dddddd;
  }

  .ant-picker {
    width: 220px !important;
    height: 32px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #dddddd;
  }

  :deep(.ant-form-item-control-input) {
    width: 220px !important;
  }
</style>
